package fr.univ.lille1.android;

import android.os.Bundle;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import fr.univ.lille1.android.AuthenticationFragment.OnSignInListener;
import fr.univ.lille1.android.auth.AuthenticationService;
import fr.univ.lille1.android.domain.User;

public abstract class BaseActivity extends SherlockFragmentActivity implements
		OnSignInListener {
	/**
	 * Handling the authentication for TagThis account. This fragment is reused
	 * through all activities in the application.
	 */
	protected AuthenticationFragment mAuthentication;
	/**
	 * User authenticated by TagThis. This user can be null if there isn't
	 * authenticated or have all informations about the user.
	 */
	protected User mUser;

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);

		mAuthentication = AuthenticationFragment.get(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_log_out, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_log_out:
			// Log out the user.
			mAuthentication.disconnect();
			AuthenticationActivity_.intent(this).start();
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onSignedIn(AuthenticationService service) {
		final String nameCurrentUser = service.getCurrentUser().getName();
		final String succeed = String.format(
				getString(R.string.sign_in_succeed), nameCurrentUser);
		Toast.makeText(getApplicationContext(), succeed, Toast.LENGTH_SHORT)
				.show();
	}

	@Override
	public void onSignInFailed() {
		mUser = null;
		Toast.makeText(getApplicationContext(), R.string.sign_in_failed,
				Toast.LENGTH_SHORT).show();
	}
}
